<template>
  <div class="chat-container">
    <!-- 侧边栏对话列表 -->
    <!-- <div class="sidebar" :class="{ 'sidebar-hidden': !showSidebar }">
      <ChatList />
    </div> -->

    <!-- 主聊天区域 -->
    <div class="main-chat" :class="{ 'sidebar-hidden': !showSidebar }">
      <!-- 聊天头部 -->
      <div class="chat-header">
        <div class="header-left">
          <div class="avatar">
            <AiAvatarIcon />
          </div>
          <div class="title">
            <h3>AI助手</h3>
            <span class="status online">在线</span>
          </div>
        </div>
        <div class="header-right">
          <button
            class="btn-icon"
            @click="toggleExpandChat"
            :title="homeStore.expandSideBox ? '还原' : '展开'"
          >
            <FullscreenIcon v-if="!homeStore.expandSideBox" />
            <ExitFullscreenIcon v-else />
          </button>
          <!-- <button class="btn-icon" @click="$emit('close')" title="关闭">
          <CloseIcon />
        </button> -->
        </div>
      </div>

      <!-- 聊天消息区域 -->
      <div :class="['chat-messages', homeStore.expandSideBox && 'expand']" ref="messagesContainer">
        <!-- 分页加载触发器 -->
        <div ref="loadTriggerRef" class="load-trigger">
          <div v-if="isLoadingMore" class="loading-more">
            <div class="loading-spinner"></div>
            <span>加载历史消息中...</span>
          </div>
          <div v-else-if="hasMore" class="has-more-hint">上滑查看更多历史消息</div>
        </div>

        <MessageItem
          v-for="(message, index) in messages"
          :key="message.id || index"
          :message="message"
          :is-waiting="
            message.id === streamingMessageId && message.role === 'assistant' && isWaiting
          "
          :is-typing="isTyping"
          @regenerate="regenerateMessage"
        />
      </div>

      <!-- 聊天输入区域 -->
      <div :class="['chat-input', homeStore.expandSideBox && 'expand']">
        <div class="input-area">
          <div v-if="chatStore.attachments.length > 0" class="input-attachment">
            <MessageAttachment
              style="border-radius: 40px"
              v-for="attachment in chatStore.attachments"
              :key="attachment.id"
              :attachment="attachment as any"
              :show-delete="true"
              @delete="handleDeleteAttachment"
            />
          </div>
          <div class="input-wrapper">
            <!-- 左侧功能按钮 -->
            <div class="input-actions">
              <button class="action-btn" @click="addAttachment" title="添加附件">
                <AttachmentIcon />
              </button>
              <button class="action-btn" @click="clearChat" title="清空对话">
                <TrashIcon />
              </button>
            </div>

            <!-- 输入框 -->
            <textarea
              v-model="inputMessage"
              placeholder="输入消息..."
              @keydown="handleKeydown"
              :disabled="isTyping"
              rows="1"
              class="message-input"
            ></textarea>

            <!-- 右侧发送按钮 -->
            <button
              class="send-btn"
              @click="isTyping ? stopGeneration() : sendMessage()"
              :disabled="!isTyping && !inputMessage.trim()"
              :class="{ 'stop-mode': isTyping }"
            >
              <SendIcon v-if="!isTyping" />
              <StopIcon v-else />
            </button>
          </div>
        </div>
      </div>
    </div>
    <!-- 关闭 main-chat -->
  </div>
</template>

<script setup lang="ts">
import {
  AiAvatarIcon,
  AttachmentIcon,
  ExitFullscreenIcon,
  FullscreenIcon,
  SendIcon,
  StopIcon,
  TrashIcon,
} from '@/icons/chat';
import { ChatMessage, type IStreamChatParams } from '@/interface/chat';
import { useChatStore } from '@/stores/chat';
import { useHomeStore } from '@/stores/home';
import { useStreamChat } from '@/utils/sse';
import { useTypewriter } from '@/utils/typewriter';
import { useScrollLoad, useScrollPosition } from '@/utils/useScrollLoad';
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import MessageAttachment from './MessageAttachment.vue';
import MessageItem from './MessageItem.vue';

const props = defineProps<{
  userName?: string;
}>();

const emit = defineEmits<{
  close: [];
  send: [message: string, questionId?: string | number];
  stop: [questionId?: string | number];
  fullscreen: [isFullscreen: boolean];
}>();

const chatStore = useChatStore();
const homeStore = useHomeStore();

// 使用store中的消息
const messages = computed(() => chatStore.currentChat.messages);

// 打字机效果
const typewriter = useTypewriter({
  speed: 80,
  showCursor: true,
  cursorChar: '|',
  startDelay: 500,
});

const inputMessage = ref('');
const isWaiting = ref(false);
const isTyping = ref(false);
const messagesContainer = ref<HTMLElement>();

const userInitial = computed(() => {
  return props.userName?.charAt(0).toUpperCase() || 'U';
});

const showSidebar = computed(() => {
  return homeStore.expandSideBox;
});

// 流式聊天功能
const { startStream, stopStream, isStreaming } = useStreamChat();

// 当前流式回复的消息ID
const streamingMessageId = ref<number | null>(null);

// 滚动位置管理
const { scrollToBottom, maintainScrollPosition } = useScrollPosition(messagesContainer);

// 分页加载功能
const {
  isLoading: isLoadingMore,
  hasMore,
  triggerRef: loadTriggerRef,
  setupObserver,
  cleanup: cleanupObserver,
  setHasMore,
} = useScrollLoad(
  async () => {
    // 加载更多消息的逻辑
    if (!chatStore.currentChatId) return false;

    const currentChatInfo = chatStore.currentChat as any;
    console.log('🚀 ~ loadMoreMessages ~ currentChatInfo:', currentChatInfo);

    if (!currentChatInfo?.pagination?.hasMore) {
      console.log('没有更多历史消息');
      return false;
    }

    await maintainScrollPosition(async () => {
      const success = await chatStore.loadMoreMessages(chatStore.currentChatId);
      if (success) {
        console.log('加载更多消息成功');
      }
    });

    return true;
  },
  {
    root: messagesContainer.value,
    rootMargin: '20px 0px 0px 0px',
    threshold: 0.1,
  }
);

// 监听messages变化，自动滚动到底部
watch(
  () => chatStore.currentChat.messages,
  () => {
    nextTick(() => {
      scrollToBottom();
    });
  },
  { deep: true }
);

// 监听当前聊天切换，重新设置观察器和同步状态
watch(
  () => chatStore.currentChatId,
  () => {
    nextTick(() => {
      setupObserver();
      // 同步 hasMore 状态
      const currentChatInfo = chatStore.currentChat as any;
      setHasMore(currentChatInfo?.pagination?.hasMore ?? true);
    });
  }
);

// 监听分页信息变化，同步 hasMore 状态
watch(
  () => (chatStore.currentChat as any)?.pagination?.hasMore,
  newHasMore => {
    if (newHasMore !== undefined) {
      setHasMore(newHasMore);
    }
  }
);

const regenerateMessage = (messageId: number) => {
  console.log('重新生成消息:', messageId);
  sendMessage(true);
};

const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault();
    sendMessage();
  }
};

const sendMessage = async (regenerate?: boolean) => {
  // 如果正在生成，则返回
  if (isTyping.value) return;
  const messageContent = inputMessage.value.trim();

  // 如果消息队列为空，则使用打字机效果更新对话标题
  if (messages.value && messages.value.length === 0) {
    // 使用打字机效果更新对话标题
    typewriter.start(messageContent).then(() => {
      chatStore.changeChatTitle(messageContent);
    });
  }
  const params: IStreamChatParams = {
    content: messageContent,
    conversation_id: chatStore.currentChatId,
    // TODO: 添加其他参数,(问题附件需要修改为对象，以便后端存储聊天记录)
  };
  let newMessage: ChatMessage;
  if (regenerate) {
    // 如果重新生成，则删除最后一条消息
    const message = chatStore.removeMessage();
    console.log('🚀 ~ regenerateMessage ~ removed message:', message);
    // 获取最后一条用户消息
    const lastUserMessage = chatStore.latestMessage;
    // 将消息内容塞进参数中
    params.content = lastUserMessage?.content || '';
    // 将附件塞进参数中
    params.params = chatStore.groupMessageAttachmentsByType(lastUserMessage?.attachments || []);
    params.params.regenerate = true;
    console.log('🚀 ~ regenerateMessage ~ params:', params);
  } else {
    // 如果消息内容为空，则返回
    if (!messageContent) return;
    // 创建新用户消息
    newMessage = new ChatMessage({
      role: 'user',
      content: messageContent,
      type: 'text',
      attachments: [],
    });
    // 添加用户消息到store
    inputMessage.value = '';
    const userMessage = chatStore.addMessage(newMessage);
    if (chatStore.attachments.length > 0) {
      // TODO: 将附件塞进用户聊天信息中展示
      userMessage.attachments = [...chatStore.attachments];
      params.params = { ...chatStore.attachmentsGroupedByType };
    }
    console.log('🚀 ~ sendMessage ~ params:', params);
  }

  // 添加空的AI回复消息，用于接收流式内容
  const aiMessage = ref(
    chatStore.addMessage(
      new ChatMessage({
        role: 'assistant',
        content: '',
        type: 'text',
      })
    )
  );

  // 设置等待状态
  isWaiting.value = true;
  streamingMessageId.value = aiMessage.value.id!;
  isTyping.value = true;
  // 流式对话开启，清除对话框中的附件
  chatStore.clearMessageAttachments();

  try {
    // 启动流式对话
    await startStream(params, {
      onChunk: (chunk: string) => {
        // 设置等待状态为false
        isWaiting.value = false;
        // 逐步更新AI回复内容
        if (aiMessage && aiMessage.value.id === streamingMessageId.value) {
          aiMessage.value.content += chunk;
        }
      },
      onComplete: () => {
        console.log('流式对话完成');
        // 设置等待状态为false
        isWaiting.value = false;
        isTyping.value = false;
        streamingMessageId.value = null;
        console.log('🚀 ~ onComplete ~ aiMessage:', aiMessage);
      },
      onError: (error: Error) => {
        console.error('流式对话错误:', error, 'chat/index.vue');
        // 设置等待状态为false
        isWaiting.value = false;
        isTyping.value = false;

        // 更新AI消息为错误信息
        if (aiMessage && aiMessage.value.id === streamingMessageId.value) {
          aiMessage.value.content = '抱歉，对话出现了问题，请稍后重试。';
        }
        streamingMessageId.value = null;
      },
    });
  } catch (error) {
    console.error('发送消息失败:', error);
    // 设置等待状态为false
    isWaiting.value = false;
    isTyping.value = false;
    streamingMessageId.value = null;

    // 显示错误信息
    if (aiMessage) {
      aiMessage.value.content = '发送消息失败，请检查网络连接后重试。';
    }
  }
};

// 停止生成对话
const stopGeneration = () => {
  // 停止流式连接
  stopStream();

  // 设置等待状态为false
  isWaiting.value = false;
  isTyping.value = false;
  streamingMessageId.value = null;

  // 如果当前有正在流式输出的消息，添加停止标识
  const currentMessages = chatStore.currentChat.messages;
  if (currentMessages && currentMessages.length > 0) {
    const lastMessage = currentMessages[currentMessages.length - 1];
    if (lastMessage.role === 'assistant' && !lastMessage.content.trim()) {
      // 如果最后一条AI消息是空的，说明流式输出被中断，更新消息内容
      lastMessage.content = '对话已停止。';
    } else if (lastMessage.role === 'assistant' && lastMessage.content.trim()) {
      // 如果已有部分内容，在末尾添加停止标识
      lastMessage.content += '\n\n[对话已停止]';
    }
  }

  // 发射停止事件给父组件
  emit('stop', chatStore.currentChatId);

  // 滚动到底部显示停止消息
  nextTick(() => {
    scrollToBottom();
  });
};

const addAttachment = () => {
  console.log('添加附件功能待实现');
};

// 删除附件
const handleDeleteAttachment = (attachmentId: number) => {
  console.log('删除附件:', attachmentId);
  // 从 chatStore 中移除附件
  chatStore.removeMessageAttachment(attachmentId);
};

const clearChat = () => {
  chatStore.clearMessages();
  // 添加欢迎消息
  chatStore.addMessage(
    new ChatMessage({
      role: 'assistant',
      content: '对话已清空，让我们重新开始吧！',
      type: 'text',
    })
  );
};

const toggleExpandChat = () => {
  homeStore.toggleExpandSideBox();
};

// 初始滚动到底部
scrollToBottom();

onMounted(() => {
  chatStore.initChat();

  // 设置分页加载的 IntersectionObserver
  nextTick(() => {
    setupObserver();
  });
});
</script>

<style lang="less" scoped>
.chat-container {
  display: flex;
  height: 100%;
  background: #ffffff;
  overflow: hidden;
}

.sidebar {
  width: 300px;
  height: 100%;
  border-right: 1px solid #e2e8f0;
  transition: all 0.3s ease;
  flex-shrink: 0;

  &.sidebar-hidden {
    width: 0;
    transform-origin: right center;
    transform: scale(0);
    opacity: 0;
    overflow: hidden;
  }
}

.main-chat {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100%;
  transition: all 0.3s ease;
  overflow: hidden;

  // &.sidebar-hidden {
  //   width: 100%;
  // }
}

.chat-header {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;

  .header-left {
    display: flex;
    align-items: center;
    gap: 12px;

    .avatar {
      width: 40px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .title {
      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
      }

      .status {
        font-size: 12px;
        opacity: 0.8;

        &.online {
          color: #4ade80;
        }
      }
    }
  }
}

.btn-icon {
  background: none;
  border: none;
  color: white;
  cursor: pointer;
  padding: 8px;
  border-radius: 8px;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover {
    background: rgba(255, 255, 255, 0.2);
    transform: scale(1.1);
  }

  &:active {
    transform: scale(0.9);
  }
}

.chat-messages {
  flex: 1;
  overflow: hidden auto;
  padding: 20px 24px;
  width: 100%;
  transition: all 0.3s;

  &.expand {
    padding-left: calc(24px + 15%);
    padding-right: calc(24px + 15%);
  }

  .load-trigger {
    padding: 10px 0;
    text-align: center;
    min-height: 40px;

    .loading-more {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      color: #667eea;
      font-size: 14px;

      .loading-spinner {
        width: 16px;
        height: 16px;
        border: 2px solid #e2e8f0;
        border-top: 2px solid #667eea;
        border-radius: 50%;
        animation: spin 1s linear infinite;
      }
    }

    .has-more-hint {
      color: #94a3b8;
      font-size: 12px;
      padding: 8px;
      background: rgba(148, 163, 184, 0.1);
      border-radius: 12px;
      display: inline-block;
    }
  }
}

.chat-input {
  width: 100%;
  transition: all 0.3s;
  font-size: 16px;
  padding: 0 24px 12px;

  &.expand {
    width: 70%;
  }

  .input-area {
    border: 1px solid #e2e8f0;
    border-radius: 30px;
    transition: all 0.2s ease;

    &:focus-within {
      border-color: #667eea;
      box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }

    .input-attachment {
      padding: 10px;
    }

    .input-wrapper {
      padding: 10px;
      display: flex;
      align-items: flex-end;
      gap: 12px;
    }

    .input-actions {
      display: flex;
      align-items: flex-end;
      gap: 4px;
      padding-bottom: 8px;

      .action-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 24px;
        height: 24px;
        border: none;
        background: transparent;
        color: #64748b;
        cursor: pointer;
        border-radius: 4px;
        transition: all 0.2s ease;

        &:hover {
          background: #e2e8f0;
          color: #667eea;
          transform: scale(1.05);
        }
      }
    }

    .message-input {
      flex: 1;
      border: none;
      outline: none;
      resize: none;
      line-height: 24px;
      max-height: 100px;
      min-height: 24px;
      padding: 8px 0;
      background: transparent;
      color: #1e293b;

      &::placeholder {
        color: #94a3b8;
      }
    }

    .send-btn {
      /* 默认发送状态样式 */
      color: white;
      border: none;
      border-radius: 50%;
      width: 40px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      flex-shrink: 0;
      box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
      position: relative;
      overflow: hidden;

      /* 发送模式悬停状态 */
      &:hover:not(:disabled):not(.stop-mode) {
        transform: scale(1.08) rotate(-2deg);
        box-shadow: 0 6px 20px rgba(102, 126, 234, 0.5);

        :deep(.send-icon) {
          .send-path-1,
          .send-path-2 {
            stroke: #5a67d8;
          }
        }
      }

      /* 停止模式 - 当 isTyping 为 true 时 */
      &.stop-mode {
        color: white;
        box-shadow: 0 2px 8px rgba(239, 68, 68, 0.4);
        animation: pulse-stop 2s infinite;

        :deep(.stop-icon) {
          .stop-square {
            fill: #ef4444;
          }
          .stop-glow-ring {
            display: none; /* 去掉发光环 */
          }
          .stop-highlight {
            display: none; /* 去掉高光效果 */
          }
          .stop-border {
            display: none; /* 去掉边框增强 */
          }
        }

        /* 停止模式悬停效果 */
        &:hover {
          transform: scale(1.05);
          border-color: #dc2626;
          background-color: rgba(239, 68, 68, 0.05);

          :deep(.stop-icon) {
            .stop-square {
              fill: url(#stopGradientHover);
              transform: scale(1.1);
            }
            .stop-glow-ring {
              r: 12;
              opacity: 0.8;
            }
          }
        }
      }

      /* 禁用状态 */
      &:disabled {
        background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
        cursor: not-allowed;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        transform: none;

        :deep(.send-icon) {
          .send-path-1,
          .send-path-2 {
            stroke: #94a3b8;
          }
        }
      }
    }
  }
}

/* 动画关键帧定义 */
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    max-height: 100vh;
    border-radius: 0;
  }

  .sidebar {
    width: 280px;

    &.sidebar-hidden {
      width: 0;
    }
  }

  .message-content {
    max-width: 85%;
  }

  .chat-header {
    padding: 12px 16px;
  }

  .chat-messages {
    padding: 16px;
  }
}
</style>
